package com.jxtc.enterprise.merchant.controller;


import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.jxtc.enterprise.common.constants.OrderPaymentStatus;
import com.jxtc.enterprise.common.mapper.OrderDetailMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 临时添加接口，后期会逐步废弃掉
 *
 * 商户小程序【数据】页面还未开发完成前，临时添加的接口，用于导出某个商户当天的所有订单
 * 商户店铺的营业数据
 */

@Deprecated
@RestController
@RequestMapping("/jxtc/enterprise/merchant/data")
@RequiredArgsConstructor
@Slf4j
public class MerchantDataController {

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @ApiResponse(responseCode = "200", description = "导出成功")
    @Operation(summary = "8.3 根据公司 ID 和日期列表将订单信息导出成 Excel", tags = {"8. 订单管理"}, operationId = "8.3")
    @GetMapping("/export")
    public void export2Excel(HttpServletResponse response, @RequestParam("phone") String phone,
                             @RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime) {
        log.info("url: /jxtc/enterprise/merchant/data/export, phone: {}, startTime: {}, endTime: {}", phone, startTime, endTime);
        List<HashMap<String, Object>> orders = orderDetailMapper.queryOrderDetailsByMerchantPhone(phone, startTime, endTime);
        export2File(response, orders, phone, startTime, endTime);
    }


    private void export2File(HttpServletResponse response, List<HashMap<String, Object>> orders, String phone, String startTime, String endTime) {

        try (ExcelWriter writer = ExcelUtil.getWriter(true)) {


            List<Map<String, Object>> data = new ArrayList<>();
            String storeName = phone;
            int idx = 1;
            for (HashMap<String, Object> orderDetail : orders) {
                String userName = (String) orderDetail.get("userName");
                String userPhone = (String) orderDetail.get("phone");
                String companyName = (String) orderDetail.get("companyName");
                String departName = (String) orderDetail.get("departName");
                storeName = (String) orderDetail.get("storeName");
                String foodPrintName = (String) orderDetail.get("foodPrintName");
                Integer quantity = (Integer) orderDetail.get("quantity");
                String foodSpec = (String) orderDetail.get("foodSpec");
                Integer salePrice = (Integer) orderDetail.get("salePrice");
                LocalDateTime createTime = (LocalDateTime) orderDetail.get("createTime");
                Integer orderStatus = (Integer) orderDetail.get("orderStatus");
                String formattedOrderStatus = OrderPaymentStatus.getNameByValue(orderStatus);
                DateTimeFormatter formmater = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedCreateTime = formmater.format(createTime);
                String orderId = (String)orderDetail.get("orderId");

                data.add(createRow(idx++, userName, userPhone, companyName, departName, storeName,
                        foodPrintName, foodSpec, quantity, salePrice, formattedCreateTime,formattedOrderStatus, orderId));
            }
            String sheetName = storeName + "-" + startTime + "至" + endTime;
            addSheet(writer, sheetName, data);

            String filename = storeName +"-" + startTime + "至" + endTime + ".xlsx";

            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
            writer.flush(response.getOutputStream(), true);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw new RuntimeException("Error while generating Excel file", e);
        }
    }

    private Map<String, Object> createRow(Integer index, String username, String phone, String companyName,
                                          String department, String storeName, String foodPrintName, String foodSpec,
                                          Integer quantity, Integer salePrice, String orderTime,
                                          String formattedOrderStatus, String orderId) {
        // 使用 LinkedHashMap 而不是 HashMap 防止标题栏乱序
        Map<String, Object> row = new LinkedHashMap<>();
        row.put("序号", index);
        row.put("用户名", username);
//        row.put("用户手机号", phone);
        row.put("公司", companyName);
        row.put("部门", department);
        row.put("店铺", storeName);
        row.put("餐品", foodPrintName);
        row.put("规格", foodSpec);
        row.put("份数", quantity);
        row.put("价格", 1.0 * salePrice / 100);
        row.put("下单时间", orderTime);
        row.put("订单状态", formattedOrderStatus);
        row.put("打印链接",
                MessageFormat.format("https://admin.enterprise.qiyetuancan.com:9091/jxtc/enterprise/merchant/printByOrderId?orderId={0}", orderId));
        return row;
    }

    private void addSheet(ExcelWriter writer, String sheetName, List<Map<String, Object>> data) {

        writer.renameSheet(sheetName);

        writer.write(data, true);

        // 获取当前工作表
        Sheet sheet = writer.getSheet();

        // 设置“餐品”这一列的宽度，索引从 0 开始
        int dishNameColumnIndex = 3;
        sheet.setColumnWidth(dishNameColumnIndex, 40 * 256);

        // 设置“下单时间”这一列的宽度
        int orderTimeColumnIndex = 5;
        sheet.setColumnWidth(orderTimeColumnIndex, 20 * 256);
    }
}


